package com.vimi8.ebb.api.product;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.dto.ProductBusinessVolumeDto;
import com.vimi8.ebb.dto.ProductTradingBusinessDto;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.EnumCategoryService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.PorductInfoService;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringCategoryCodeUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by renyong on 2017/2/7.
 */
@RestController
@RequestMapping("/front/product")

@Controller
public class FrontProductController {
    protected Logger logger =  LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PorductInfoService porductInfoService;
    @Autowired
    private EnumCategoryService enumCategoryService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private ElectricityBusinessService electricityBusinessService;

    @ApiOperation(value = "查询所有产品信息",notes = "查询所有产品信息",response = ProductInfo.class,tags = {"产品信息（前端）"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/allproductinfo/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<ProductInfo>>> getProductAllList(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
                                                                                    @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
                                                                                    @ApiParam(value = "按交易量排序", required = false) @RequestParam(value = "tradeBusinessOrder", required = false) String tradeBusinessOrder,
                                                                              @ApiParam(value = "按交易额排序", required = false) @RequestParam(value = "tradeVolumnOrder", required = false) String tradeVolumnOrder,
                                                                                    @ApiParam(value = "产品名称", required = false) @RequestParam(value = "productName", required = false) String productName) {
        logger.info("Title="+"查询所有产品信息"+","+"method="+"/allproductinfo/");
        int count = 0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setCurrentPage(start);
        if(start<1){
            pagesUtil.setCurrentPage(1);
        }
        Paginator<List<ProductInfo>> paginator=null;
        try {
            int total = porductInfoService.productInfoTotal(productName);
            pagesUtil.setTotalCount(total);
            logger.info("total:////////////////////////////////"+total);
            List<ProductInfo> trainInfos = porductInfoService.getProductInfoList(productName,(pagesUtil.getCurrentPage()-1)*size,size,tradeBusinessOrder,tradeVolumnOrder);
            for (int i=0;i<trainInfos.size();i++){
                if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())&&!StringUtils.isEmpty(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()))){
                    trainInfos.get(i).setEnumCategoryName(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()).getCategoryName());
                }

            }
            logger.info("total:////////////////////////////////"+trainInfos);
            paginator=new Paginator<List<ProductInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),trainInfos);
            return new HttpResponseEntity<Paginator<List<ProductInfo>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @ApiOperation(value = "查询产品TOP10分析",notes = "查询产品TOP10分析",response = ProductTradingBusinessDto.class,tags = {"产品信息（前端）"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/analyze/",method = RequestMethod.GET)
    public HttpResponseEntity<List<ProductTradingBusinessDto>> getAnalyzeInfo(@ApiParam(value = "交易量", required = false) @RequestParam(value = "businessVolume", required = false) String businessVolume,
                                                                              @ApiParam(value = "交易金额", required = false) @RequestParam(value = "tradingVolume", required = false) String tradingVolume,
                                                                              @ApiParam(value = "地址code", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
                                                                              @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime) {
        logger.info("Title="+"查询产品TOP10分析"+","+"method="+"/analyze/");
        if (null!=addressCode&&!"".equals(addressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
            addressCode= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            logger.info("addressCode="+addressCode);
        }
        List<ProductTradingBusinessDto> paginator=null;
        try {
            List<ProductTradingBusinessDto> trainInfos = null;
            if (businessVolume!=null&&businessVolume.equals("")){
                trainInfos = porductInfoService.getAnalyzeInfoBusinessVolume(addressCode,startTime);
                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        if (!StringUtils.isEmpty(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()))){
                            trainInfos.get(i).setEnumCategoryName(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()).getCategoryName());
                        }
                    }
                }
            }else if(tradingVolume!=null&&tradingVolume.equals("")){
                trainInfos = porductInfoService.getAnalyzeInfoTradingVolume(addressCode,startTime);
                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        if (!StringUtils.isEmpty(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()))){
                            trainInfos.get(i).setEnumCategoryName(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()).getCategoryName());
                        }
                    }
                }
            }else {
                trainInfos = porductInfoService.getAnalyzeInfoTradingVolume(addressCode,startTime);
                logger.info("trainInfos="+trainInfos);
                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        if (!StringUtils.isEmpty(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()))){
                            trainInfos.get(i).setEnumCategoryName(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()).getCategoryName());
                        }
                    }
                }
                logger.info("trainInfos="+trainInfos);
            }
            return new HttpResponseEntity<List<ProductTradingBusinessDto>>(trainInfos,HttpStatus.OK);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @ApiOperation(value = "查询产品TOP10分析列表",notes = "查询产品TOP10分析列表",response = ProductTradingBusinessDto.class,tags = {"产品信息（前端）"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/analyze/list/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<ProductTradingBusinessDto>>> getAnalyzeInfoList(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
                                                                                  @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
                                                                                  @ApiParam(value = "地址code", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
                                                                              @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime) {
        logger.info("Title="+"查询产品TOP10分析"+","+"method="+"/analyze/");
        if (null!=addressCode&&!"".equals(addressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
            addressCode= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            logger.info("addressCode="+addressCode);
        }
        Paginator<List<ProductTradingBusinessDto>> paginator=null;
        int count = 0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setCurrentPage(start);
        if(start<1){
            pagesUtil.setCurrentPage(1);
        }
        try {
            int total = porductInfoService.productInfoTopListTotal(addressCode,startTime);
            pagesUtil.setTotalCount(total);
            List<ProductTradingBusinessDto> trainInfos = null;
            trainInfos = porductInfoService.getAnalyzeInfoList(addressCode,startTime,(pagesUtil.getCurrentPage()-1)*pagesUtil.getPageSize(),pagesUtil.getPageSize());
            logger.info("trainInfos="+trainInfos);
            for (int i=0;i<trainInfos.size();i++){
                if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                    if (!StringUtils.isEmpty(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()))){
                        trainInfos.get(i).setEnumCategoryName(enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId()).getCategoryName());
                    }
                }
            }
            logger.info("trainInfos="+trainInfos);
            paginator=new Paginator<List<ProductTradingBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),trainInfos);
            return new HttpResponseEntity<Paginator<List<ProductTradingBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @ApiOperation(value = "交易量汇总",notes = "交易量汇总",response = ProductBusinessVolumeDto.class,tags = {"产品信息（前端）"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/businessVolume/",method = RequestMethod.GET)
    public HttpResponseEntity<HashMap<String,Object>> getBusinessVolumeInfo(@ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime) {
        logger.info("Title="+"交易量汇总"+","+"method="+"/businessVolume/");
        String code =  "520600000000";
        HashMap<String,Object> map = new HashMap<>();

        List<Object> businessList = new ArrayList<>();//交易量
        List<Object> tradingList = new ArrayList<>();//销售量
        List<Object> addressList = new ArrayList<>();//地址

        try {
            //利用工具类生成带通配符的地址代码
            String geoCode = SubStringUtil.separateGeoCode(code,"3");
            logger.info("======================================code:" + geoCode);
            List<GeoCodings> geoCodingsList = geoCodingsService.getGeoCodingsByCode(code,geoCode);
            logger.info("==============================geoCodings:"+geoCodingsList);
            for (int i=0;i<geoCodingsList.size();i++){
                HashMap<String,Object> hashMap = porductInfoService.getProductBusinessVolume(geoCodingsList.get(i).getId(),startTime);
                if(hashMap!=null){
                    businessList.add(hashMap.get("businessVolume"));
                }else{
                    businessList.add(0);
                }
                //装入地址
                addressList.add(geoCodingsList.get(i).getGeoName());
            }
            map.put("businessList",businessList);
            map.put("addressList",addressList);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
         return new HttpResponseEntity<HashMap<String, Object>>(map,HttpStatus.OK);

    }

    @ApiOperation(value = "交易额汇总",notes = "交易额汇总",response = ProductBusinessVolumeDto.class,tags = {"产品信息（前端）"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/tradingVolume/",method = RequestMethod.GET)
    public HttpResponseEntity<HashMap<String, Object>> gettradingVolumeInfo(@ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime) {
        logger.info("Title=" + "交易额汇总" + "," + "method=" + "/tradingVolume/");
        String code = "520600000000";
        HashMap<String, Object> map = new HashMap<>();

        List<Object> tradingList = new ArrayList<>();//销售量
        List<Object> businessList = new ArrayList<>();//销售量
        List<Object> addressList = new ArrayList<>();//地址

        try {
            //利用工具类生成带通配符的地址代码
            String geoCode = SubStringUtil.separateGeoCode(code, "3");
            logger.info("======================================code:" + geoCode);
            List<GeoCodings> geoCodingsList = geoCodingsService.getGeoCodingsByCode(code, geoCode);
            logger.info("====================geoCodings:" + geoCodingsList);
            for (int i = 0; i < geoCodingsList.size(); i++) {
                HashMap<String, Object> hashMap = porductInfoService.getProductBusinessVolume(geoCodingsList.get(i).getId(),startTime);
                HashMap<String, Object> hashMap2 = porductInfoService.getProductTradingVolume(geoCodingsList.get(i).getId(),startTime);

                HashMap<String, Object> hashMap3 = porductInfoService.getEbbProductTradingVolume(geoCodingsList.get(i).getId(),startTime);
                if(hashMap!=null){
                    businessList.add(hashMap.get("businessVolume"));
                }else{
                    businessList.add(0);
                }
                Object tradingVolumn=0;
                if(hashMap2!=null){
                    //tradingList.add(hashMap2.get("tradingVolume"));
                    tradingVolumn=hashMap2.get("tradingVolume");
                }
                logger.info("geoCoding="+geoCodingsList.get(i).getId()+",startTime="+startTime+",tradingVolumn="+tradingVolumn);
                if (hashMap3!=null){
                    Float volume = Float.valueOf(tradingVolumn.toString()) + Float.valueOf(hashMap3.get("ebbVolume").toString());
                    tradingVolumn=volume.toString();
                }
                tradingList.add(tradingVolumn);
                //装入地址
                addressList.add(geoCodingsList.get(i).getGeoName());
            }
            map.put("businessList", businessList);
            map.put("tradingList", tradingList);
            map.put("addressList", addressList);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<HashMap<String, Object>>(map, HttpStatus.OK);
    }


}
